<!DOCTYPE html>
<!--Created By OSGBLab(http://www.osgblab.com)-->
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport"
    content="width=device-width, initial-scale = 1, maximum-scale = 1, minimum-scale = 1, user-scalable = no">
  <title>Titgroup-web</title>
  <script src="/Cesium/Cesium.js"></script>
  <style>
    @import url(/Cesium/Widgets/widgets.css);

    html,
    body,
    #OSGBLab_Container {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }

    #coordinateDisplay {
      position: absolute;
      top: 10px;
      left: 10px;
      width: 200px;
      height: 200px;
      background-color: rgba(0, 0, 0, 0.2);
      color: white;
      padding: 10px;
      overflow-y: auto;
      z-index: 1000;
    }
  </style>
</head>

<body>
  <div id="OSGBLab_Container"></div>
  <div id="coordinateDisplay"></div>
</body>
<script>
  function IsMobile () {
    var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
    var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
    return mobile;
  }
  Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5OTc4MTFiYS1hYzhlLTQ3ZjYtYWJmMi1hODMwMWMxZGRiYTQiLCJpZCI6ODU1NDksImlhdCI6MTY1Mzc5NDc5N30.ldTi8bF3XvSOgnZrMITokRW4kE3i8Mwbarhk5OQbPsI';
  var terrain = Cesium.createDefaultTerrainProviderViewModels();
  var viewer = new Cesium.Viewer('OSGBLab_Container', {
    animation: false,
    vrButton: true,
    timeline: false,
    sceneModePicker: false,
    scene3DOnly: true,
    infoBox: true,
    terrainProviderViewModels: terrain,
    selectedTerrainProviderViewModel: terrain[0]
  });
  var stages = viewer.scene.postProcessStages;
  viewer.scene.brightness = viewer.scene.brightness || stages.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
  viewer.scene.brightness.enabled = true;
  viewer.scene.brightness.uniforms.brightness = Number(1.2);
  viewer.scene.globe.depthTestAgainstTerrain = false;
  var boundingSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(114.191719, 37.00696374, 233.0319478), 541.1534535);
  viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function (cmd) {
    viewer.camera.flyToBoundingSphere(boundingSphere);
    cmd.cancel = true;
  });
  viewer.camera.flyToBoundingSphere(boundingSphere, { duration: 0 });
  // 开启地形
  viewer.terrainProvider = Cesium.createWorldTerrain();
  const addWorldTerrainAsync = async () => {
    try {
      const terrainProvider = await Cesium.CesiumTerrainProvider.fromUrl(
        '//data.mars3d.cn/terrain',
        {
          requestWaterMask: true,
          requestVertexNormals: true,
        }
      );
      viewer.terrainProvider = terrainProvider;
    } catch (error) {
      // console.log(`Failed to add world imagery: ${error}`);
    }
  };
  addWorldTerrainAsync();

  const moveEvent1 = () => {
    // 实体加载
    let entities = viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(114.191719, 37.00696374, 233),
      point: {
        color: Cesium.Color.fromCssColorString('#60d169'),
        pixelSize: 15,
        // 实体不被地形遮挡参数设置
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        clampToGround: false,
      },
      label: {
        text: 'test',
        font: '14pt Source Han Sans CN', //字体样式
        fillColor: Cesium.Color.fromCssColorString('#00FF00'), //字体颜色
        style: Cesium.LabelStyle.FILL, //label样式
        scale: 1.0,
        outlineWidth: 2,
        verticalOrigin: Cesium.VerticalOrigin.CENTER, //垂直位置
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT, //水平位置
        pixelOffset: new Cesium.Cartesian2(10, 0), //偏移
        // 实体不被地形遮挡参数设置
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      },
    });
    let pointDraged = null;
    let leftDownFlag;
    let originalHeight = 0;
    // 左键按下事件
    function leftDownAction (e) {
      console.log('左键按下');
      pointDraged = viewer.scene.pick(e.position); //选取当前的entity
      leftDownFlag = true;
      if (pointDraged) {
        viewer.scene.screenSpaceCameraController.enableRotate = false; //锁定相机
        const position = pointDraged.id.position.getValue(
          Cesium.JulianDate.now()
        );
        originalHeight = Cesium.Cartographic.fromCartesian(position).height;
      }
    }
    // 鼠标移动事件
    function mouseMoveAction (e) {
      if (leftDownFlag === true && pointDraged != null) {
        console.log('鼠标移动', e);
        // let ray = viewer.camera.getPickRay(e.endPosition);
        // let cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        // pointDraged.id.position.setValue(cartesian);

        var cartesian = viewer.scene.camera.pickEllipsoid(
          e.endPosition,
          viewer.scene.globe.ellipsoid
        );
        if (cartesian) {
          const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          const height = viewer.scene.globe.getHeight(cartographic);
          pointDraged.id.position.setValue(
            Cesium.Cartesian3.fromRadians(
              cartographic.longitude,
              cartographic.latitude,
              233
            )
          );
        }
      }
    }
    //清除鼠标事件
    function cancelDrag () {
      viewer.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOWN
      );
      viewer.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_UP
      );
      viewer.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.MOUSE_MOVE
      );
    }
    // 左键抬起事件
    function leftUpAction (e) {
      console.log('左键抬起');
      leftDownFlag = false;
      pointDraged = null;
      viewer.scene.screenSpaceCameraController.enableRotate = true; //解锁相机
      cancelDrag();
      moveEvent1();
    }
    // 移动点
    function movePoint () {
      viewer.screenSpaceEventHandler.setInputAction((e) => {
        leftDownAction(e);
      }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
      viewer.screenSpaceEventHandler.setInputAction((e) => {
        leftUpAction(e);
      }, Cesium.ScreenSpaceEventType.LEFT_UP);
      viewer.screenSpaceEventHandler.setInputAction((e) => {
        mouseMoveAction(e);
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    }
    movePoint();
  };

  // moveEvent1()
  function method2 () {
    // 创建一个空中实体，初始位置为经度 -75.59777，纬度 40.03883，高度 100000 米
    var entity = viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(114.191719, 37.00696374, 233),
      point: {
        pixelSize: 20,
        color: Cesium.Color.RED
      }
    });

    // 获取canvas的引用
    var scene = viewer.scene;
    var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);

    // 鼠标拖拽事件
    var isDragging = false;
    var initialPosition;
    var origin = null

    // 鼠标按下事件：开始拖动
    handler.setInputAction(function (movement) {
      origin = viewer.scene.pick(movement.position); //选取当前的entity
      viewer.scene.screenSpaceCameraController.enableRotate = false; //锁定相机

      var ray = viewer.camera.getPickRay(movement.position);
      var intersection = viewer.scene.globe.pick(ray, viewer.scene);

      if (Cesium.defined(intersection)) {
        // 记录初始位置
        initialPosition = intersection;
        isDragging = true;
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    // 鼠标移动事件：更新实体的位置
    handler.setInputAction(function (movement) {
      if (isDragging) {
        var ray = viewer.camera.getPickRay(movement.endPosition);
        var intersection = viewer.scene.globe.pick(ray, viewer.scene);

        if (Cesium.defined(intersection)) {
          // 获取当前的经纬度，保持固定高度
          var cartographic = Cesium.Cartographic.fromCartesian(intersection);

          origin?.id.position.setValue(Cesium.Cartesian3.fromDegrees(
            Cesium.Math.toDegrees(cartographic.longitude),
            Cesium.Math.toDegrees(cartographic.latitude),
            223 // 固定高度
          ));
          console.log(origin.id.position);
        }
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // 鼠标松开事件：停止拖动
    handler.setInputAction(function () {
      isDragging = false;
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }
  // method2()
  const addClcikEvent = () => {
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (movement) {
      // 获取鼠标点击位置的屏幕坐标
      const cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        // 将笛卡尔坐标转换为地理坐标（经纬度）
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
        // 输出经纬度信息
        console.log(`经度: ${longitude}, 纬度: ${latitude}`);
        var entity = viewer.entities.add({ // 在该位置添加点
          position: cartesian,
          point: {
            pixelSize: 10,
            color: Cesium.Color.YELLOW
          },
          label: {
            text: `${longitude},${latitude}`,
            font: '14pt Source Han Sans CN', //字体样式
            fillColor: Cesium.Color.fromCssColorString('#00FF00'), //字体颜色
            style: Cesium.LabelStyle.FILL, //label样式
            backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 0.8),
            scale: 1.0,
            showBackground: true,                //是否显示背景颜色
            style: Cesium.LabelStyle.FILL,        //label样式
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,//垂直位置
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,//水平位置
            pixelOffset: new Cesium.Cartesian2(10, 0),            //偏移
            disableDepthTestDistance: Number.POSITIVE_INFINITY // 禁用深度测试，使点始终显示在地球表面上
          },
        });
        // 坐标展示
        // 获取显示坐标的div元素
        var coordinateDiv = document.getElementById('coordinateDisplay');

        // 创建新的坐标信息段落
        var newCoordinate = document.createElement('p');
        newCoordinate.textContent = `Longitude: ${longitude.toFixed(6)}, Latitude: ${latitude.toFixed(6)}`;

        // 将新的坐标信息添加到div中
        coordinateDiv.appendChild(newCoordinate);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  };
  addClcikEvent()
</script>

</html>